/**
 * CMIS User interface using EXTJS
 *
 * This file contains the UI elements for the CMIS Interface using EXTJS
 * @author Alex Griessel <alex@webnetix.co.za>
 * @version 1.0
 * @package CmisController
 */
Ext.QuickTips.init();

/**
 * Insert document into workspace
 */

function insertFile(n) {
    req = n.attributes['objectId'];
    ExternalComponent.insertDocument(req, n);
    Ext.getCmp('tabPanel').activate(Ext.getCmp('tabPanel').items.length - 1);
}

/**
 * Common Function used for opening resources from TreePanel
 */

function openFile(n, expand) {
    expand = (typeof expand == "undefined") ? false : true;

    if (expand && /ditamap/.test(n.text)) {
        Ext.getCmp('browseTabPanel').add([{
            xtype: 'treepanel',
            title: n.text,
            closable: true,
            width: 'auto',
            useArrows: true,
            animate: true,
            enableDD: false,
            containerScroll: true,
            border: false,
            dataUrl: '?r=cmis/getMapNodes',
            requestMethod: 'GET',
            rootVisible: false,
            root: {
                nodeType: 'async',
                text: 'CMIS',
                draggable: false,
                id: n.attributes['objectId']
            },
            contextmenu: contextMenu,
            listeners: contextMenuListeners


        }]);
        Ext.getCmp('browseAccordion').getLayout().setActiveItem(1);
        Ext.getCmp('browseTabPanel').activate(Ext.getCmp('browseTabPanel').items.length - 1);

    } else {
	var audiences = Ext.getCmp("audience").getValue();
        var filter = "";
        for (var i = 0; i < audiences.length; i++) {
        	filter += "&filter[audience][]=" + audiences[i].getName();
        }
        req = n.attributes['objectId'] + filter;
        ExternalComponent.insertDocument(req, n);
        Ext.getCmp('tabPanel').activate(Ext.getCmp('tabPanel').items.length - 1);
    }
}

/**
 * Conditional Processing Menu
 */
var conditionalMenu = new Ext.menu.Menu({
        width:200,
style : {
                    'margin'           : "0px 0px 1px 0px",
                    'display'          : 'block',
                    'text-align'       : 'left'

              },
	    items: null,
            listeners: {
                        itemclick: function(item) {

                                var n = item.parentMenu.parentMenu.contextNode;
                                switch(item.id) {
                                        case "insert":
                                                var audiences = Ext.getCmp("audience").getValue();
                                                var filter = "";
                                                for (var i = 0; i < audiences.length; i++) {
                                                        filter += "&filter[audience][]=" + audiences[i].getName();
                                                }
                                                req = n.attributes['objectId'] + filter;
                                                break;
                                }
                                ExternalComponent.insertDocument(req, n);
                        }
                }
        });
/*
 * Get Audiences from server
 *
*/
Ext.Ajax.request({
                                url: '?r=cmis/getAudiences',
                                success: function(resp) {
                                        var arr = Ext.decode(resp.responseText);
                                                Ext.each(arr, function(o) {
                                                conditionalMenu.add(o);
                                                });
                                }

                        });



/**
 * Toolbar Panel
 */
var toolbarPanel = new Ext.Toolbar({
    id: 'toolbarPanel',
    title: 'Toolbar',
    region: 'north',
	height:30,
    items: [{
		text:'Options',
		menu: new Ext.menu.Menu({
			items:[{
				text:'Conditional Processing',
				menu: conditionalMenu
			}]
		})
	},'->',{
        	text: 'Log off',
        	listeners: {
           		 click: function (n) {
                		window.location = '?r=site/logout';
            		}
        	}
    }]
});


/**
 * Properties Panel
 */
var propertiesPanel = new Ext.Panel({
    id: 'propertiesPanel',
    title: 'Properties',
    width: 250,
    region: 'east'
});


var contextMenuListeners = {
    contextmenu: function (node, e) {
        node.select();
        var c = node.getOwnerTree().contextmenu;
        c.contextNode = node;
        c.showAt(e.getXY());
    },
    click: function (n) { /*Ext.Msg.alert('Navigation Tree Click', 'You clicked: "' + n.attributes.id + '"');*/
        if (n.attributes.cls == "document") {
            openFile(n);
        }
    },
                                        beforenodedrop : function(n) {
                                                Ext.Msg.confirm('Checkout', 'Would you like to checkout ' + n.dropNode.text + '?', function (answer) {
                                                        Ext.Ajax.request({
                                                                url:'?r=cmis/copyfile',
                                                                method: 'GET',
                                                                params: {
                                                                        id: n.dropNode.attributes["objectId"],
                                                                        dst: n.target.attributes["objectId"],
                                                                        filename: n.dropNode.text
                                                                },
                                                                success: function(response) {
									n.target.reload();
                                                                        alert("Checked out :)");
                                                                },
                                                                failure: function (response, opts) {
                                                                        alert(response.responseText);


                                                                }

                                                        });
                                                        n.dropNode.attributes['objectId'];
                                                        return false;
                                                });
                                                return false;

                                        }

};
var contextMenu = new Ext.menu.Menu({
    items: [{
	id:'tree-refresh',
	text:'Refresh'
	},'-',{
        id: 'file-open',
        text: 'Open'
    },{
	id:'insert',
	text:'Insert'
	},{
        id: 'file-preview',
        text: 'Preview'
    },
    {
        id: 'file-expand',
        text: 'Expand'
    },
    {
        id: 'file-edit',
        text: 'Edit'
    },'-',{
	id:'conditional',
	text:'Conditional',
	menu: conditionalMenu
	},'-',
    {
        id: 'file-comment',
        text: 'Comment'
    }, '-',
    {
        id: 'workflow',
        text: 'Workflow',
        menu: new Ext.menu.Menu({
            items: [{
                id: 'workflow-start',
                text: 'Start ad-hoc',
                disabled: true
            },
            {
                id: 'send-review',
                text: 'Send for Review',
                disabled: true
            }]
        })
    }, '-',
    {
        id: 'file-send',
        text: 'Send to',
        menu: new Ext.menu.Menu({
            items: [{
                id: 'send-mail',
                text: 'Mail recipient',
                disabled: true
            },
            {
                id: 'send-zip',
                text: 'Compressed (zipped) folder',
                disabled: true
            }]
        })
    }, '-',
    {
        id: 'file-checkout',
        text: 'Checkout/Checkout',
        disabled: true
    },
    {
        id: 'file-lock',
        text: 'Lock/Unlock',
        disabled: true
    },
    {
        id: 'file-restore',
        text: 'Restore previous version',
        disabled: true
    }, '-',
    {
        id: 'file-rename',
        text: 'Rename'
    },
    {
        id: 'file-delete',
        text: 'Delete'
    }, '-',
    {
        id: 'file-new',
        text: 'New',
        menu: new Ext.menu.Menu({
            items: [{
                id: 'folder-create',
                text: 'Folder'
            }, '-',
            {
                id: 'map-create',
                text: 'Map',
                topicType: 'map'
            },
            {
                id: 'topic-create',
                text: 'Topic',
                topicType: 'topic'
            },
            {
                id: 'concept-create',
                text: 'Concept',
                topicType: 'concept'
            },
            {
                id: 'task-create',
                text: 'Task',
                topicType: 'task'
            },
            {
                id: 'reference-create',
                text: 'Reference',
                topicType: 'reference'
            },
            {
                id: 'composite-create',
                text: 'Composite',
                topicType: 'composite'
            }],
            listeners: {
                itemclick: function (item) {
                    var n = item.parentMenu.parentMenu.contextNode;
                    switch (item.id) {
                    case 'topic-create':
                    case 'task-create':
                    case 'reference-create':
                    case 'composite-create':
                    case 'map-create':
                    case 'concept-create':
                        createTopic = new Ext.Window({
                            title: "Create New " + item.text,
                            id: 'createTopicWin',
                            width: 250,
                            height: 250,
                            items: [{
                                id: "createTopicDialog",
                                xtype: 'form',
                                url: '?r=cmis/addFile',
                                padding: 10,
                                method: 'POST',
                                labelWidth: 65,
                                labelAlign: 'top',
                                items: [{
                                    xtype: 'textfield',
                                    id: 'itemName',
                                    fieldLabel: item.text + ' Title',
                                    allowBlank: false,
                                    blankText: "Enter Topic Title",
                                    enableKeyEvents: true,
                                    listeners: {
                                        keyUp: function (field, event) {
                                            fileExt = (Ext.getCmp("itemType").getValue() == "map") ? '.ditamap' : ".xml";
                                            Ext.getCmp("fileName").setValue(field.getValue().replace(/[^a-z0-9\s]/ig, "").replace(/\s/g, "_").toLowerCase() + fileExt);
                                        }
                                    }
                                },
                                {
                                    xtype: 'textfield',
                                    id: 'fileName',
                                    fieldLabel: 'Filename',
                                    allowBlank: false,
                                    blankText: "Enter Filename"
                                },
                                {
                                    xtype: 'combo',
                                    id: 'itemType',
                                    editable: false,
                                    fieldLabel: 'Type',
                                    typeAhead: true,
                                    triggerAction: 'all',
                                    lazyRender: true,
                                    mode: 'local',
                                    value: item.topicType,
                                    listeners: {
                                        select: function (combo, record, index) {
                                            Ext.getCmp("createTopicWin").setTitle("Create New " + record.data['displayText']);
                                            Ext.getCmp("itemName").label.update(record.data['displayText'] + " Title:");
                                        }
                                    },
                                    store: new Ext.data.ArrayStore({
                                        id: 0,
                                        fields: ['myId', 'displayText'],
                                        data: [
                                            ['topic', 'Topic'],
                                            ['concept', 'Concept'],
                                            ['task', 'Task'],
                                            ['reference', 'Reference'],
                                            ['composite', 'Composite'],
                                            ['map', 'Map']
                                        ]
                                    }),
                                    valueField: 'myId',
                                    displayField: 'displayText'
                                }],
                                buttons: [{
                                    text: 'Create',
                                    handler: function () {
                                        Ext.getCmp('createTopicDialog').getForm().submit({
                                            clientValidation: true,
                                            url: '?r=cmis/addFile',
                                            method: 'POST',
                                            params: {
                                                cmisId: n.attributes['objectId']
                                            },
                                            success: function (form, action) {
                                                n.reload();
                                                Ext.getCmp("createTopicWin").close();
                                            },
                                            failure: function (form, action) {
                                                switch (action.failureType) {
                                                case Ext.form.Action.CLIENT_INVALID:
                                                    Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                                    break;
                                                case Ext.form.Action.CONNECT_FAILURE:
                                                    Ext.Msg.alert('Failure', 'Ajax communication failed');
                                                    break;
                                                case Ext.form.Action.SERVER_INVALID:
                                                    Ext.Msg.alert('Failure', action.result.msg);
                                                }
                                            }
                                        });
                                    }

                                },
                                {
                                    text: 'Cancel',
                                    handler: function () {
                                        createTopic.close();
                                    }
                                }]
                            }]
                        }).show();
                        break;
                    case 'folder-create':
                        createFolder = new Ext.Window({
                            title: "Create Folder",
                            id: 'createFolderWin',
                            width: 200,
                            height: 150,
                            items: [{
                                id: "createFolderDialog",
                                xtype: 'form',
                                url: '?r=cmis/createFolder',
                                padding: 10,
                                method: 'POST',
                                labelWidth: 65,
                                labelAlign: 'top',
                                items: [{
                                    xtype: 'textfield',
                                    id: 'itemName',
                                    fieldLabel: 'Folder Name',
                                    allowBlank: false,
                                    blankText: "Enter Folder Name"
                                }],
                                buttons: [{
                                    text: 'Create',
                                    handler: function () {
                                        Ext.getCmp('createFolderDialog').getForm().submit({
                                            clientValidation: true,
                                            url: '?r=cmis/addFolder',
                                            method: 'POST',
                                            params: {
                                                cmisId: n.attributes['objectId']
                                            },
                                            success: function (form, action) {
						n.reload();
                                                Ext.getCmp("createFolderWin").close();
                                            },
                                            failure: function (form, action) {
                                                switch (action.failureType) {
                                                case Ext.form.Action.CLIENT_INVALID:
                                                    Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                                    break;
                                                case Ext.form.Action.CONNECT_FAILURE:
                                                    Ext.Msg.alert('Failure', 'Ajax communication failed' + action.result.msg);
                                                    break;
                                                case Ext.form.Action.SERVER_INVALID:
							    Ext.Msg.alert('Failure', action.result.msg);
							}
						    }
						});
					    }

					},
					{
					    text: 'Cancel',
					    handler: function () {
						createFolder.close();
					    }
					}]
				    }]
				}).show();

				break;
			    }
			}
		    }
		})
	    }, '-',
	    {
		id: 'file-properties',
		text: 'Properties',
		disabled: true
	    }],
	    listeners: {
		itemclick: function (item) {
		    var n = item.parentMenu.contextNode;
		    switch (item.id) {
		    case 'send-mail':
			req = "?r=cmis/show&id=" + n.attributes['objectId'];
			//	    	ExternalComponent.insertDocument(req,'x');
			mailWin = new Ext.Window({
			    title: 'About',
			    padding: 10,
			    width: 200,
			    height: 130,
			    html: 'CMIS Browser<br />Version: 1.0<br />Copyright DITALabs &copy; 2010',
			    buttons: [{
				text: 'OK',
				listeners: {
				    click: function () {
					mailWin.close();
				    }
				}
			    }]
			}).show();
			break;
		    case 'file-comment':
			commentWindow = new Ext.Window({
			    title: "Comment",
			    padding: 10,
			    width: 300,
			    height: 300,
			    buttons: [{
				text: 'Add Comment',
				listeners: {
				    click: function () {
					commentWindow.close();
				    }
				}
			    },
			    {
				text: "Cancel",
				listeners: {
				    click: function () {
					commentWindow.close();
				    }
				}
			    }]
			}).show();
			break;
		    case 'tree-refresh':
			n.reload();
			break;
		    case 'file-rename':
			//ge.editNode = n;
                //ge.startEdit(n.ui.textNode);
                alert('Not Implemented');
                break;
            case 'file-open':
                if (n.attributes.cls == "document") {
                    openFile(n);
                }
                break;
            case 'file-expand':
                if (n.attributes.cls == "document") {
                    openFile(n, true);
                }
                break;
            case 'file-edit':
                req = n.attributes['objectId'];
                ExternalComponent.editDocument(req, n);
                break;
            case 'file-preview':
		 var audiences = Ext.getCmp("audience").getValue();
                 var filter = "";
                 for (var i = 0; i < audiences.length; i++) {
                 	filter += "&filter[audience][]=" + audiences[i].getName();
                 }
                 req = n.attributes['objectId'] + filter;

                ExternalComponent.previewDocument(req, n);
                break;
            case 'file-delete':
                Ext.Msg.confirm('Are you sure?', 'Would you like to delete ' + n.text + '?', function (answer) {
                    if (answer == "yes") {
                        Ext.Ajax.request({
                            url: '?r=cmis/delete&id=' + n.attributes['objectId'],
                            success: function (response, options) {
				var obj = Ext.decode(response.responseText);
				    if (obj.success) {
					    n.remove();
				    } else {
					    Ext.Msg.alert("Failed to delete item", obj.msg);
				    }
                            },
			    failure: function(response) {
				    Ext.Msg.alert('Failure', response);
			    },
                            params: {
                                id: n.attributes['objectId']
                            }
                        });

                    }
                });
                //	req = "?r=cmis/delete&path=" + n.attributes['cmisid'];
                break;
            }
        }
    }
});


/**
 * Used for filtering on workspace trees 
 */
var myFilter = new Ext.tree.TreeFilter();

/**
 * Common panel header functions
 */
var workspaceFuntions = [{
                                        id:'minus',
					qtip:'Collapse Tree',
                                        handler: function(ev, toolEl, panel, tc) {
                                                        panel.collapseAll();
                                        }
                                },{
                                        id:'plus',
					qtip:'Expand Tree',
                                        handler: function(ev, toolEl, panel, tc) {
                                                        panel.expandAll();
                                        }
                                },{
                                        id:'refresh',
					qtip:'Refresh Tree',
                                        handler: function(ev, toolEl, panel, tc) {
                                                        panel.getRootNode().reload();
                                        }
                                }];

/**
 * Workspace common toolbar
 */
var workspacePersonalTbar =  new Array(['->',{
                                        id:'searchQ1',
					xtype:'textfield',
					name:'qPersonal',
                                        emptyText:'Find a File...',
                                        enableKeyEvents : true,
                                        listeners:{
                                                keyup: function(obj, e) {
                                                        if (obj.getValue() == "") {
                                                                myFilter.clear();
                                                        } else {
								myMatch = new RegExp(obj.getValue(),"gi");
                                                                myFilter.filter(myMatch,'text',Ext.getCmp("treePersonalPanel").getRootNode());
                                                        }
                                                }
                                        }
                                }]);
var workspaceTbar =  new Array(['->',{
                                        id:'searchQ2',
					xtype:'textfield',
					name:'qPublic',
                                        emptyText:'Find a File...',
                                        enableKeyEvents : true,
                                        listeners:{
                                                keyup: function(obj, e) {
                                                        if (obj.getValue() == "") {
                                                                myFilter.clear();
                                                        } else {
								myMatch = new RegExp(obj.getValue(),"gi");
                                                                myFilter.filter(myMatch,'text',Ext.getCmp("treePanel").getRootNode());
                                                        }
                                                }
                                        }
                                }]);
/**
 * Tab Panel used for main content area
 */
var tabPanel = new Ext.TabPanel({
    id: 'tabPanel',
    title: 'Main Content',
    activeTab: 0,
    margin: '0 0 0 0',
    padding: 0,
    defaults: {
        padding: 0
    },
    // index or id
    autoScroll: true,
    items: [{
        id: 'initTab',
        closable: true,
        title: 'default',
        html: "<iframe src='index.php?r=cmis/showhtml&id=workspace://SpacesStore/2cb2e7a3-febb-43cf-96c9-8dfb4a715a59' width='100%' height='100%' border='0' style='border:0px'/>"
    }],
    collapsible: false,
    region: 'center',
    margins: '0 0 0 0'
});

/**
 * Browse Panel
 */
var browsePanel = new Ext.Panel({
    title: 'CMIS Browser',
    region: 'west',
    layout: 'fit',
    padding: 0,
    width: 250,
    autoScroll: true,
    border: true,
    flex: 2,
    items: [{
        layout: 'accordion',
        id: 'browseAccordion',
        activeItem: 1,
        border: false,
        layoutConfig: {
            titleCollapse: false,
            animate: true
        },
        items: [{
            title: 'Search',
            id: 'searchPanel',
            xtype: 'treepanel',
            border: false,
            layout: 'fit',
            collapsible: true,
            xtype: 'treepanel',
            enableDrag: true,
            autoScroll: true,
            split: true,
            loader: new Ext.tree.TreeLoader({
                dataUrl: '?r=cmis/search',
                requestMethod: 'GET',
                listeners: {
                    reload: function (q) {
                        this.baseParams.q = q;
                        Ext.getCmp("searchPanel").root.reload();
                    }
                }

            }),
            rootVisible: false,
            root: {
                nodeType: 'async',
                expanded: true,
                text: 'Ext JS',
                draggable: false
            },

                    contextmenu: contextMenu,
                    listeners: contextMenuListeners,
            tbar: [{
                xtype: 'textfield',
                name: 'search',
                id: 'q',
                fieldLabel: 'Search'
            },
            {
                xtype: 'button',
                text: 'Search',
                listeners: {
                    click: function () {
                        Ext.getCmp("searchPanel").getLoader().fireEvent('reload', Ext.getCmp('q').getValue());
                    }
                }
            }]
        },
        {
            title: "Browser",
            layout: 'fit',
            border: false,
            items: [{
                xtype: 'tabpanel',
                tabPosition: 'bottom',
                border: false,
                id: 'browseTabPanel',
                activeItem: 0,
                items: [{
                title: 'Repository',
			layout:'border',
			defaults: {
				collapsible: false,
				split: true,
				bodyStyle: 'padding:0px',
				autoScroll:true,
                    		containerScroll: true,
                    		contextmenu: contextMenu,
                    		listeners: contextMenuListeners,
                    		useArrows: true,
                    		pathSeparator: '>',
                    		width: 'auto',
                    		animate: true,
                    		enableDD: true,
                    		border: false,
                    		rootVisible: false
			},
			items:[{
                    		id: 'treePersonalPanel',
                    		title: 'User Workspace',
                    		xtype: 'treepanel',
				region:'north',
                    		dataUrl: '?r=cmis/browse',
                    		requestMethod: 'GET',
				height:200,
                                tools: workspaceFuntions,
				tbar: workspacePersonalTbar,
                    		root: {
                        		nodeType: 'async',
                        		text: 'CMIS',
                        		draggable: false,
                        		id: '/User Homes'
                    		}
			},{
                    		id: 'treePanel',
                    		title: 'Public Workspace',
                    		xtype: 'treepanel',
				region:'center',
                    		dataUrl: '?r=cmis/browse',
                    		requestMethod: 'GET',
                                tools: workspaceFuntions,
				tbar: workspaceTbar,
                    		root: {
                        		nodeType: 'async',
                        		text: 'CMIS',
                        		draggable: false,
                        		id: '/'
                    		}
                	}]
		}]
            }]
        }]
    }]
});

/**
 * Tree editor 
 */

/*
var ge = new Ext.tree.TreeEditor(Ext.getCmp('treePanel'), {}, {
	allowBlank:false,
	blankText:'A name is required',
	selectOnFocus:true
});	
*/
/**
 * EXTJS init
 */

Ext.onReady(function () {
    if ((extenderType != "msoffice" && extenderType != "xmetal" ) && extenderType != "lookup" ) {

        var viewport = new Ext.Viewport({
            layout: 'border',
            defaults: {
                collapsible: false,
                split: true,
                bodyStyle: 'padding:15px',
                margins: '5 5 0 5',
                cmargins: '5 0 0 0'
            },
            items: [
            browsePanel, toolbarPanel, tabPanel]
        });
    } else {
        var viewport = new Ext.Viewport({
            layout: 'vbox',
            layoutConfig: {
                align: 'stretch',
                pack: 'start'
            },
            items: [toolbarPanel, browsePanel]
        });
    }


});
/*
	Loading default user environment
*/
Ext.Ajax.request({
	url: '?r=cmis/getUsername',
	success: function(resp) {
		Ext.getCmp("treePersonalPanel").selectPath(">/User Homes>/User Homes/" + resp.responseText + ">/");
	}
});

